package org.cy.shixun.controller;


import org.cy.shixun.dto.CartShowDto;
import org.cy.shixun.service.CartService;
import org.cy.shixun.utils.RedisUtil;
import org.cy.shixun.vo.ProductShow;
import org.cy.shixun.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 类名称：CartController
 * 描述：购物车控制器
 *
 * @author: cy
 * @data: 2023/06/29
 */
@CrossOrigin
@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;
    @Autowired
    private RedisUtil redisUtil;
    @PostMapping("join")
    public R join(@RequestBody ProductShow productShow, HttpServletRequest request){
        String token = request.getHeader("tk");
        int res = cartService.join(productShow, token);
        if(res==0){
            return R.error("加入购物车失败");
        }else{
            return R.success("加入购物车成功");
        }
    }

    /**
     *购物车商品展示
     * @param request 请求
     * @return {@link R }
     */
    @GetMapping("/selectCart")
    public R CartShow(HttpServletRequest request){
        String token=request.getHeader("tk");
        String account = redisUtil.getString(token);
        List<CartShowDto> cartShowDtos = cartService.cartShow(account);
        return R.success(cartShowDtos);
    }

    @GetMapping("deleteGoods")
    public R deleteGoods(int goodsId,String goodsSize,HttpServletRequest request){
        String token=request.getHeader("tk");
        String account = redisUtil.getString(token);
        if(goodsId<=0|| StringUtils.isEmpty(account)||StringUtils.isEmpty(goodsSize)){
            return R.error("删除失败，请重试");
        }
        cartService.deleteGoods(goodsId,account,goodsSize);
        return R.success("删除成功");
    }

}

